import cn.hutool.json.JSONUtil;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zhong
 */
public class MyWebSocketClient extends WebSocketClient {

    public MyWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake data) {
        System.out.println("WebSocket连接已打开。");
    }

    @Override
    public void onMessage(String message) {
        System.out.println("收到消息: " + message);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("WebSocket连接已关闭。");
    }

    @Override
    public void onError(Exception ex) {
        System.err.println("WebSocket连接发生错误：" + ex.getMessage());
    }

    /**
     * 连接定时检查
     */
    public void startReconnectTask(long delay,
                                   TimeUnit unit) {
        System.out.println("WebSocket 心跳检查");
        this.send("{\"type\":\"99\"}".getBytes());
        // 以下为定时器,建议使用自定义线程池，或交给框架处理（spring）
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleWithFixedDelay(() -> {
            // 检查逻辑：判断当前连接是否连通
            if (!this.isOpen()) {
                System.out.println("WebSocket 开始重连......");
                // 重置连接
                this.reconnect();
                // 以下为错误示范
                //this.close();
                //this.connect();
            }
        }, 0, delay, unit);
    }
	// 测试
    public static void main(String[] args) throws URISyntaxException {
        // 服务地址
        URI uri = new URI("ws://127.0.0.1:7080/websocket");
        // 创建客户端
        MyWebSocketClient myWebSocketClient = new MyWebSocketClient(uri);
        // 建立连接
        myWebSocketClient.connect();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // 开启 定时检查
        for (int i = 0; i < 1000; i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("type","99");
            map.put("deviceId","10001");
            myWebSocketClient.send(JSONUtil.toJsonStr(map));
            System.out.printf("心跳"+JSONUtil.toJsonStr(map));
            HashMap<String, String> map1 = new HashMap<String, String>();
            map1.put("type","1");
            map1.put("deviceId","10001");
            map1.put("imei","123123");
            map1.put("iotCardno","123123");
            myWebSocketClient.send(JSONUtil.toJsonStr(map1));
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        try {
            Thread.sleep(1000000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
